跳到主要内容

JZ66 机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8

这题还是挺简单的,之前没有看题目,以为是 row + col 的和,实际问的是它们位数的和,说来看排行榜上的解法居然还去计算了 - 的坐标,完全是浪费时间,只需计算 + 就行了

public class Solution {
public int movingCount(int threshold, int rows, int cols) {
// 因为可能会有重复的,所以创建一个 mark 标识
byte[][] mark = new byte[rows][cols];
return dfs(threshold, mark, rows, cols, 0, 0);
}

// 深搜
private int dfs(int threshold, byte[][] mark, int rows, int cols, int row, int col) {
if (row >= rows ||
col >= cols ||
cal(row) + cal(col) > threshold ||
mark[row][col] == 1) return 0;

mark[row][col] = 1;

int res =
dfs(threshold, mark, rows, cols, row + 1, col) +
dfs(threshold, mark, rows, cols, row, col + 1);
return 1 + res;
}

// 计算位数数字
private int cal(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
}